package com.yuqing.myblogServe.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuqing.myblogServe.common.lang.Const;
import com.yuqing.myblogServe.common.lang.PageBean;
import com.yuqing.myblogServe.common.lang.Result;
import com.yuqing.myblogServe.dao.entity.Article;
import com.yuqing.myblogServe.dao.entity.ArticleComment;
import com.yuqing.myblogServe.dao.entity.ArticleLikesRecord;
import com.yuqing.myblogServe.dao.entity.SysUser;
import com.yuqing.myblogServe.dto.ArticleDto;
import com.yuqing.myblogServe.service.ArticleCommentReplyService;
import com.yuqing.myblogServe.service.ArticleLikesRecordService;
import com.yuqing.myblogServe.service.ArticleService;
import com.yuqing.myblogServe.service.SysUserService;
import com.yuqing.myblogServe.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lyq
 * @date 2023/12/2
 **/

@RestController
@RequestMapping("/home")
@Api(value = "首页管理 controller" ,tags = {"首页接口"})
public class HomeController extends BaseController {

    @Autowired
    ArticleService articleService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    ArticleLikesRecordService articleLikesRecordService;

    @Autowired
    ArticleCommentReplyService articleCommentReplyService;

    @Autowired
    UserUtil userUtil;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 首页展示文章
     */
    @GetMapping("/list")
    @ApiOperation(value = "获取文章列表")
    public Result showArticle(Principal principal) {
        Page<Article> pageData = articleService.page(getPage(),new QueryWrapper<Article>().orderByDesc("update_date"));
        List<Article> articles = pageData.getRecords();
        if(principal != null) {
            SysUser sysUser = sysUserService.getByUsername(principal.getName());
            for (Article article : articles) {
                System.out.print(article.getArticleId());
                // 是否已经点赞
                if(articleLikesRecordService.isLike(article.getArticleId(), sysUser.getId())) {
                    article.setIsLike(1);
                } else {
                    article.setIsLike(0);
                }
            }
        }

        return Result.succ(pageData);
    }

    /**
     * 文章详情
     */
    @GetMapping("/detail/{articleId}")
    @ApiOperation(value = "获取文章详情")
    public Result detailArticle(@PathVariable String articleId, Principal principal) {
        Article article =  articleService.getArticleByArtId(articleId);
        if(principal!= null) {
            SysUser sysUser = sysUserService.getByUsername(principal.getName());
            // 是否已经点赞
            if(articleLikesRecordService.isLike(article.getArticleId(), sysUser.getId())) {
                article.setIsLike(1);
            } else {
                article.setIsLike(0);
            }
        }

        return Result.succ(article);
    }

    /**
     * 文章点赞榜
     */
    @GetMapping("/likesRank")
    @ApiOperation(value = "获取文章点赞榜")
    public Result ArticleRank() {

        return Result.succ(articleService.getLikesRank());
    }

    /**
     * 评论列表
     */
    @GetMapping("/commentList")
    @ApiOperation(value = "评论列表")
    public Result<PageBean<ArticleComment>> commentList(@RequestParam("articleId") String articleId,
                                                        @RequestParam(value = "curr", defaultValue = "1") int page,
                                                        @RequestParam(value = "limit", defaultValue = "6") int pageSize) {

        return Result.succ(articleService.listCommentByPage(null, articleId, page, pageSize));
    }

    /**
     * 评论回复列表
     */
    @GetMapping("/commentReplyList")
    @ApiOperation(value = "回复评论列表")
    public Result commentReplyList(@RequestParam("commentId") String commentId) {

        return Result.succ(articleCommentReplyService.getCommentReplyList( commentId));

    }

    @PostMapping("/updateUser")
    @ApiOperation(value = "修改用户")
    public Result update(@Validated @RequestBody SysUser sysUser) {
        sysUser.setUpdated(LocalDateTime.now());
        sysUserService.updateById(sysUser);
        SysUser updateUser = sysUserService.getById(sysUser.getId());
        return Result.succ(updateUser);
    }

    @PostMapping("/register")
    @ApiOperation(value = "注册用户")
    public Result save(@Validated @RequestBody SysUser sysUser) {
        sysUser.setCreated(LocalDateTime.now());
        sysUser.setStatu(Const.STATUS_ON);
        if (StrUtil.isBlank(sysUser.getPassword())) {
            // 初始默认密码
            sysUser.setPassword(Const.DEFULT_PASSWORD);
            return Result.fail("密码不能为空");
        }
        String password = passwordEncoder.encode(sysUser.getPassword());
        sysUser.setPassword(password);
        // 默认头像
        sysUser.setAvatar(Const.DEFULT_AVATAR);
        sysUserService.save(sysUser);
        return Result.succ(sysUser);
    }

}
